package com.hulk.boot.common.tool.fastdfs;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


/**
 * @author cmt
 * @描述: FastDFS分布式文件系统操作客户端 .
 * @创建时间: 2016-4-26,下午8:13:49 .
 * @版本号: V1.0 .
 */

@Slf4j
public class FastDFSFactoryBean implements FactoryBean<StorageClient1>, InitializingBean, DisposableBean {

	@Setter
	@Getter
	private String configFileName; //引入文件名称
	//private FastDFS fastDFS;
	private	StorageClient1 storageClient1;

	@Override
	public void afterPropertiesSet() throws Exception {
		try {
			log.info("=== CONF_FILENAME:" + configFileName);
			ClassLoader classloader = Thread.currentThread()
					.getContextClassLoader();
			String filePath = classloader.getResource(configFileName).getFile();
			
			log.info("classpath:{}, absolutePath:{}", configFileName,
					filePath);
			ClientGlobal.init(filePath);
			
		    log.info("DFS init finished success");
		    
			TrackerClient trackerClient = new TrackerClient(
					ClientGlobal.g_tracker_group);
			TrackerServer trackerServer = trackerClient.getConnection();
			if (trackerServer == null) {
				log.error("getConnection return null");
			}
			StorageServer storageServer = trackerClient
					.getStoreStorage(trackerServer);
			if (storageServer == null) {
				log.error("getStoreStorage return null");
			}
			storageClient1 = new StorageClient1(trackerServer,
					storageServer);
			 log.info("DFS connect finished success");
			//fastDFS = new FastDFS(storageClient1);

		} catch (Exception e) {
			log.error("", e);
		}

	}

	@Override
	public StorageClient1 getObject()  {
		return storageClient1;
	}

	@Override
	public Class<?> getObjectType() {
		return (this.storageClient1 != null ? this.storageClient1.getClass() : StorageClient1.class);
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	public void destroy() throws Exception {
		log.warn("storageClient1 is destroy failed");;
	}
}
